﻿using McpDotNet.Server;
using Newtonsoft.Json;
using System.ComponentModel;
using System.Data;
using System.Text;

namespace AspNetCoreSseServer.Tools
{
    [McpToolType]
    public class DbTools
    {
        [McpTool, Description("获取数据库中所有表信息")]
        public static string GetAllTables()
        {
            List<string> list = new List<string>();
            Dictionary<string, string> TableInfo = new Dictionary<string, string>();
            var tables = DbContext.Db.DbMaintenance.GetTableInfoList(false);//true 走缓存 false不走缓存
            foreach (var table in tables)
            {
                TableInfo.Add(table.Name, table.Description);
            }
            string jsonStr = JsonConvert.SerializeObject(TableInfo);
            return jsonStr;
        }
        [McpTool, Description("获取表中列的信息")]
        public static string GetTableInformation(string table)
        {
            List<string> list = new List<string>();
            Dictionary<string, string> ColumnInfo = new Dictionary<string, string>();
            var Columns = DbContext.Db.DbMaintenance.GetColumnInfosByTableName(table, false);//true 走缓存 false不走缓存
            foreach (var Column in Columns)
            {
                ColumnInfo.Add(Column.DbColumnName, Column.ColumnDescription);
            }
            string jsonStr = JsonConvert.SerializeObject(ColumnInfo);
            return jsonStr;
        }

        [McpTool, Description("执行sql语句获得结果")]
        public static string ExecuteSQL(string sql)
        {
            var dt = DbContext.Db.Ado.GetDataTable(sql);
            return DataTableToJson(dt);
        }


        public static string DataTableToJson(DataTable table)
        {
            var JsonString = new StringBuilder();
            if (table.Rows.Count > 0)
            {
                JsonString.Append("[");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    JsonString.Append("{");
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        if (j < table.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == table.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == table.Rows.Count - 1)
                    {
                        JsonString.Append("}");
                    }
                    else
                    {
                        JsonString.Append("},");
                    }
                }
                JsonString.Append("]");
            }
            return JsonString.ToString();
        }
    }
}
